/*
 * @Author: CodeHare
 * @Date: 2023-10-16 20:47:17
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-23 13:57:58
 * @Description: EMS控制指令组件
 */
import 'dart:async';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/rectangle_ems_romote_control/rectangle_control_instruct/rectangle_control_instruct_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/rectangle_ems_romote_control/rectangle_ems_instruction_set_params.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/formats.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class RectangleControlInstructController extends GetxController {
  DeviceServices deviceServices = Get.find<DeviceServices>();
  ProductDetailModel productDetailModel = ProductDetailModel();
  RectangleControlInstructModel model = RectangleControlInstructModel();
  SettingReqParams requestParams = SettingReqParams();

  /// 设备 ID
  String? deviceId;

  int? productId;

  /// 订阅 websocket
  UseSubsribe subscribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? subscription;
  late Stream<Map<String, dynamic>> broadcastStream;

  @override
  void onInit() {
    super.onInit();
    deviceId = Get.arguments['deviceId'].toString();
    productId = Get.arguments['productId'];

    model.canReset = productId != ProductIDType.ems.value;

    /// socket
    broadcastStream = subscribe
        .start([int.parse(deviceId!)], true)
        .stream
        .asBroadcastStream();

    subscription = broadcastStream.listen((data) {
      model.instructSocketMap = data;
      // print("socket控制按钮 ${model.instructSocketMap}");

      model.instructSocketMap.forEach((key, value) {
        if (key == 'sysStart') {
          model.sysStartStatus = value.toString();
        } else if (key == 'sysStop') {
          model.sysStopStatus = value.toString();
        } else if (key == 'sysReset') {
          model.sysRestStatus = value.toString();
        } else if (key == 'bmsClose') {
          model.bmsCloseStatus = value.toString();
        } else if (key == 'bmsBreak') {
          model.bmsBreakStatus = value.toString();
        } else if (key == 'manualAutomaticSwitch') {
          model.manualAutomaticSwitcStatus = value.toString();
        } else if (key == 'parallelOffGridMode') {
          model.parallelOffGridModeSwitcStatus = value == 0 ? '1' : '0';
        }

        update();
      });
    });
  }

  /// 弹出框文本状态
  String judgeDialogText(index) {
    final label = model.instructList(productId)[index].label;
    if (label == 'siteMonitor.systemStartup'.tr) {
      return "${ResKey.deviceTheCurrentSystemIs.tr} ${model.sysStartStatus == "0" ? 'common.stop'.tr : 'common.activate'.tr} ${'common.status'.tr}，${ResKey.deviceWhetherToExecuteSystem.tr} ${'common.activate'.tr} ${ResKey.deviceOrder.tr}?";
    } else if (label == 'siteMonitor.systemHalt'.tr) {
      return "${ResKey.deviceTheCurrentSystemIs.tr} ${model.sysStopStatus == "0" ? 'common.stop'.tr : 'common.activate'.tr} ${'common.status'.tr}，${ResKey.deviceWhetherToExecuteSystem.tr} ${'common.stop'.tr} ${ResKey.deviceOrder.tr}?";
    } else if (label == 'siteMonitor.systemReset'.tr) {
      // 系统复位
      return ResKey.deviceWhetherExecuteSystemResetCommand.tr;
    } else if (label == 'BMS ${'siteMonitor.mainContactorClosed'.tr}') {
      // BMS主接触器闭合
      return "${ResKey.deviceCurrentBMSMainContactorIs.tr} ${model.bmsCloseStatus == '0' ? ResKey.mineUserManagerUserInvalid.tr : ResKey.thingsClose.tr} ${'common.status'.tr}，${ResKey.deviceWhetherExecuteBMSTheMainContactorIs.tr} ${ResKey.thingsClose.tr}${ResKey.deviceOrder.tr}?";
    } else if (label == "BMS ${'siteMonitor.mainContactorDisconnected'.tr}") {
      // BMS主接触器断开
      return "${ResKey.deviceCurrentBMSMainContactorIs.tr} ${model.bmsBreakStatus == '0' ? ResKey.mineUserManagerUserInvalid.tr : ResKey.thingsBreak.tr} ${'common.status'.tr},${ResKey.deviceWhetherExecuteBMSTheMainContactorIs.tr} ${ResKey.thingsBreak.tr}${ResKey.deviceOrder.tr}?";
    } else if (label == 'siteMonitor.manualAutomaticSwitch'.tr) {
      return "${ResKey.deviceCurrentSystemModeIs.tr} ${model.manualAutomaticSwitcStatus == '0' ? ResKey.thingsHandMovement.tr : ResKey.thingsAutomatic.tr} ${'common.status'.tr}，${ResKey.deviceWhetherExecuteManualAutomaticCommand.tr}?"; //手/自动切换
    } else {
      return "${ResKey.deviceCurrentSystemModeIs.tr} ${Formates.parallelGridFormat(model.parallelOffGridModeSwitcStatus)} ${'common.status'.tr}，${ResKey.deviceWhetherGridSwitch.tr}?"; //手/自动切换
    }
  }

  /// 收集控制指令请求参数
  Map<String, dynamic>? collectParams(item, String? deviceId) {
    final label = item.label;
    if (label == 'siteMonitor.systemStartup'.tr) {
      // 系统启动
      return StartingSystem().trigger(deviceId, requestParams);
    } else if (label == 'siteMonitor.systemHalt'.tr) {
      //系统停止
      return StopingSystem().trigger(deviceId, requestParams);
    } else if (label == 'siteMonitor.systemReset'.tr) {
      //系统复位
      return ResettingSystem().trigger(deviceId, requestParams);
    } else if (label == 'siteMonitor.mainContactorClosed'.tr) {
      //BMS主接触器闭合
      return BMSMainContactorClosed().trigger(deviceId, requestParams);
    } else if (label == 'siteMonitor.mainContactorDisconnected'.tr) {
      // BMS主接触器断开
      return BMSMainContactorDisconnected().trigger(deviceId, requestParams);
    } else if (label == 'siteMonitor.manualAutomaticSwitch'.tr) {
      return ManualAutomaticSwitching().trigger(deviceId, requestParams);
    } else {
      return ParallelOffGridSwitching().trigger(deviceId, requestParams);
    }
  }

  /// 下发指令接口
  Future sendCommand(context, params) => Configs.httpClient.requestWithLoading(
        () async {
          await deviceServices.deviceRemoteSetting(params);
          FuncUtils.requestTipsDislog(context, ResKey.executeSuccess.tr, true);
          update();
        },
        onError: (err) {
          FuncUtils.requestTipsDislog(context, ResKey.executeFailure.tr, false);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          return true;
        },
      );

  /// 按动按钮
  void pushSwitch(item, value) {
    item.open = value;

    update();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    subscription!.cancel();
    subscribe.close();
  }
}
